package com.chatplus.application.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.domain.entity.account.InviteCodeEntity;
import com.chatplus.application.domain.entity.account.InviteLogEntity;
import com.chatplus.application.domain.request.PlusPageRequest;
import com.chatplus.application.domain.response.InviteCodeListResponse;
import com.chatplus.application.domain.response.InviteCodeDetailResponse;
import com.chatplus.application.domain.response.PlusPageResponse;
import com.chatplus.application.service.account.InviteCodeService;
import com.chatplus.application.service.account.InviteLogService;
import com.chatplus.application.web.basecontroller.BaseController;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 邀请API
 */
@Validated
@RestController
@RequestMapping("/api/invite")
@Tag(name = "邀请API", description = "邀请API")
public class InviteApiController extends BaseController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(InviteApiController.class);
    private final InviteCodeService inviteCodeService;

    private final InviteLogService inviteLogService;

    public InviteApiController(InviteCodeService inviteCodeService, InviteLogService inviteLogService) {
        this.inviteCodeService = inviteCodeService;
        this.inviteLogService = inviteLogService;
    }

    @GetMapping("/code")
    @Operation(summary = "获取用户邀请码")
    public InviteCodeDetailResponse code() {
        InviteCodeEntity inviteCodeEntity = inviteCodeService.getByUserId(getUserId());
        if (inviteCodeEntity == null) {
            String code = "";
            for (int i = 0; i < 10; i++) {
                code = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 8);
                if (inviteCodeService.getByCode(code) == null) {
                    break;
                }
            }
            inviteCodeEntity = new InviteCodeEntity();
            inviteCodeEntity.setUserId(getUserId());
            inviteCodeEntity.setCode(code);
            inviteCodeEntity.setRegNum(0);
            inviteCodeEntity.setHits(0);
            inviteCodeService.save(inviteCodeEntity);
        }
        return BeanUtil.copyProperties(inviteCodeEntity, InviteCodeDetailResponse.class);
    }

    /**
     * 邀请列表
     * {"page":1,"page_size":10}
     * {"code":0,"data":{"items":[],"page":1,"page_size":10,"total":0,"total_page":0}}
     */
    @PostMapping("/list")
    @Operation(summary = "邀请列表")
    public PlusPageResponse<InviteCodeListResponse> list(@RequestBody PlusPageRequest plusPageRequest) {
        PageParam pageParam = new PageParam(plusPageRequest.getPage(), plusPageRequest.getPageSize());
        Page<InviteLogEntity> inviteLogsPage = inviteLogService.page(pageParam.toPage(), Wrappers.<InviteLogEntity>lambdaQuery()
                .eq(InviteLogEntity::getInviterId, getUserId())
                .orderByDesc(InviteLogEntity::getCreatedAt));
        List<InviteLogEntity> inviteLogsList = inviteLogsPage.getRecords();
        if (CollUtil.isEmpty(inviteLogsList)) {
            return new PlusPageResponse<>(plusPageRequest.getPage(), plusPageRequest.getPageSize(), 0, 0, Lists.newArrayList());
        }
        List<InviteCodeListResponse> inviteCodeListResponseList = inviteLogsList.stream().map(item -> {
            InviteCodeListResponse inviteCodeListResponse = BeanUtil.copyProperties(item, InviteCodeListResponse.class);
            inviteCodeListResponse.setCreatedAt(item.getCreatedAt().getEpochSecond());
            return inviteCodeListResponse;
        }).toList();

        return new PlusPageResponse<>(plusPageRequest.getPage(), plusPageRequest.getPageSize()
                , inviteLogsPage.getPages(), inviteLogsPage.getTotal(), inviteCodeListResponseList);
    }

    @GetMapping("/hits")
    @Operation(summary = "访问邀请码")
    @SaIgnore
    public String hits(@RequestParam(value = "code", required = false) String code) {
        if (StringUtils.isEmpty(code)) {
            return "ok";
        }
        inviteCodeService.update(new LambdaUpdateWrapper<InviteCodeEntity>().eq(InviteCodeEntity::getCode, code).setSql("hits = hits + 1"));
        return "访问成功";
    }
}
